package com.jiubodou.myoauth2.controller;

import com.alibaba.fastjson2.JSON;
import com.jiubodou.myoauth2.oauth2class.jiubodou.JiuBoDouAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.HashSet;

/**
 * @ClassName JiuBoDouController
 * @Description
 * @Author huyingliang
 * @Date 2023/5/12 11:25
 */
@RestController
@RequestMapping("/jiubodou")
public class JiuBoDouController {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @PostMapping("/login")
    public String jiubodou() throws HttpRequestMethodNotSupportedException {

        String username="username-jiubodou";/*正常来说这里应该是前端传过来的 我这里就简化了一下*/
        String password="123456";
        String code="code-jiubodou";
        HashSet<GrantedAuthority> grantedAuthorities = new HashSet<>();

        JiuBoDouAuthenticationToken jiuBoDouAuthenticationToken = new JiuBoDouAuthenticationToken(username,password,code,grantedAuthorities);

        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("grant_type","jiubodou_grant_type");
        stringStringHashMap.put("username",username);
        stringStringHashMap.put("password",password);
        stringStringHashMap.put("code",code);

        jiuBoDouAuthenticationToken.setClientId("jiubodou_clientId");
        jiuBoDouAuthenticationToken.setDetails(stringStringHashMap);

        ResponseEntity<OAuth2AccessToken> postedAccessToken = tokenEndpoint.postAccessToken(jiuBoDouAuthenticationToken, stringStringHashMap);
        return JSON.toJSONString(postedAccessToken);
    }

}
